import { addDeptAndUserApi, editDeptAndUserApi } from "@/api/approval/approvalManagement";

import { message } from "ant-design-vue";

export default function OperationHook(state: any) {
  const { formState, loading, formRef, emit, getDeptOpts, type } = state;

  const onSubmit = () => {
    formRef.value.validate().then(() => {
      const params = {
        ...formState
      };
      let requestFn;
      if (type.value === 1) {
        requestFn = addDeptAndUserApi;
        Reflect.deleteProperty(params, "id");
      } else {
        requestFn = editDeptAndUserApi;
      }
      loading.value = true;
      requestFn(params)
        .then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            emit("submit");
          }
        })
        .finally(() => {
          loading.value = false;
        });
    });
  };
  const resetForm = () => {
    formRef.value.resetFields();
    emit("update:visible", false);
  };

  const addHandle = () => {
    formState.approvalList.push({
      approvalType: 0,
      deptId: undefined,
      userIdList: []
    });
  };
  const deleteHandle = (index: number) => {
    formState.approvalList.splice(index, 1);
  };

  const changeCompany = () => {
    formState.bizProportion = 10 - formState.companyProportion;
  };

  const changePerson = () => {
    formState.companyProportion = 10 - formState.bizProportion;
  };

  const changeApprovalType = (item: any) => {
    if (item.userIdList.length === item.UserOpts.length) {
      item.approvalType = 0;
    } else {
      item.approvalType = 1;
    }
  };

  const changeDep = (e: string, item: any) => {
    item.userIdList = [];
    getDeptOpts.value.map((t: any) => {
      if (t.id === e) {
        item.UserOpts = t.userList;
        t.userList.map((a: any) => {
          item.userIdList.push(a.userId);
        });
      }
    });
    changeApprovalType(item);
  };

  const changeUser = (item: any) => {
    changeApprovalType(item);
  };
  return {
    resetForm,
    onSubmit,
    addHandle,
    deleteHandle,
    changeCompany,
    changePerson,
    changeDep,
    changeUser
  };
}
